package ppa.application.dom;

import java.io.File;
import java.io.IOException;
import java.security.KeyStore.Builder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import ppa.application.model.Step;

public class XMLParser {

	private List<Document> listDocument;
	private List<File> listFiles;
	private DocumentBuilder constructeur;

	Document game = null;

	public XMLParser() throws ParserConfigurationException, SAXException,
			IOException {
		
		
		/*
		 *		DocumentBuilderFactory fabrique;
				fabrique = DocumentBuilderFactory.newInstance();
								constructeur = fabrique.newDocumentBuilder();

 constructeur.parse(list[i]));
		 * */

		DocumentBuilderFactory fabrique;
		File directory = new File("xml/");

		File[] list = directory.listFiles();
		listFiles = new ArrayList<File>();
		listDocument = new ArrayList<Document>();

		for (int i = 0; i < list.length; i++) {
			if (list[i].getName().endsWith(".xml")) {
				listFiles.add(list[i]);
				fabrique = DocumentBuilderFactory.newInstance();
				constructeur = fabrique.newDocumentBuilder();
//				constructeur.newDocument()
				listDocument.add(constructeur.parse(list[i]));
			}
		}
	}

	public List<Document> getDocument() {
		return listDocument;
	}

	public List<File> getFileList() {
		return listFiles;
	}

	public List<String> getGames() {

		List<String> list = new ArrayList<String>();

		for (Document document : listDocument) {
			Element racine = document.getDocumentElement();

			list.add(racine.getAttribute("name"));
		}

		return list;

	}

	public Step nodeToStep(Node n) {

		Step step = new Step();

		if (n != null) {

			NodeList list = n.getChildNodes();

			for (int i = 0; i < list.getLength(); i++) {

				if (list.item(i) instanceof Element) {
					Element e = ((Element) list.item(i));
					if (e.getTagName() == "code") {
						NodeList fils = list.item(i).getChildNodes();
						for (int j = 0; (j < fils.getLength()); j++) {
							step.setCode(Integer.parseInt(fils.item(j)
									.getNodeValue()));
						}
					}
					if (e.getTagName() == "exposition") {
						NodeList fils = list.item(i).getChildNodes();
						for (int j = 0; (j < fils.getLength()); j++) {
							step.setExposition(fils.item(j).getNodeValue());
						}
					}
					if (e.getTagName() == "question") {
						NodeList fils = list.item(i).getChildNodes();
						for (int j = 0; (j < fils.getLength()); j++) {

							if (fils.item(j) instanceof Element) {

								Element f = ((Element) fils.item(j));
								if (f.getTagName() == "label") {
									NodeList child = fils.item(j)
											.getChildNodes();
									for (int k = 0; (k < child.getLength()); k++) {
										step.getQuestion().setLabel(
												child.item(k).getNodeValue());
									}
								}
								if (f.getTagName() == "choice") {
									NodeList child = fils.item(j)
											.getChildNodes();
									for (int k = 0; (k < child.getLength()); k++) {
										if (child.item(k) instanceof Element) {
											Element g = ((Element) child
													.item(k));
											if (g.getTagName() == "answer") {
												step.getQuestion()
														.getNum()
														.add(Integer.parseInt(g
																.getAttribute("num")));
												step.getQuestion()
														.getChoice()
														.add(child
																.item(k)
																.getFirstChild()
																.getNodeValue());

											}
										}
									}
								}
							}

						}
					}
					if (e.getTagName() == "next") {
						NodeList fils = list.item(i).getChildNodes();
						for (int j = 0; (j < fils.getLength()); j++) {
							if (fils.item(j) instanceof Element) {
								Element f = ((Element) fils.item(j));
								if (f.getTagName() == "test") {
									step.getNext()
											.getValue()
											.add(Integer.parseInt(f
													.getAttribute("value")));
									NodeList child = fils.item(j)
											.getChildNodes();
									for (int k = 0; k < child.getLength(); k++) {
										if (child.item(k) instanceof Element) {
											Element g = ((Element) child
													.item(k));
											if (g.getTagName() == "codereponse") {
												step.getNext()
														.getCode()
														.add(Integer
																.parseInt(child
																		.item(k)
																		.getFirstChild()
																		.getNodeValue()));
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		return step;
	}

	public Node getNodebySituationCode(int code) {
		
		NodeList situationlist = game.getDocumentElement().getChildNodes();

		for (int i = 0; i < situationlist.getLength(); i++) {
			if (situationlist.item(i) instanceof Element) {
				if (Integer.parseInt(situationlist.item(i).getFirstChild()
						.getNextSibling().getFirstChild().getNodeValue()) == code) {

						return situationlist.item(i);
	
					

				}
			}
		}
		return null;
	}
	public void removeNodeBySituationCode(int code){
		game.getDocumentElement().removeChild(getNodebySituationCode(code));
		
	}
	public void replaceNodeBySituationCode(int code, Node n){
		game.getDocumentElement().replaceChild(n, getNodebySituationCode(code));
		
	}

	public static void afficher(Node n) {
		if (n.getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
			System.out.print(n.getNodeValue());
		} else if (n instanceof Comment) {
			System.out.print("<!--" + n.getNodeValue() + " -->");
		} else if (n instanceof Element) {
			Element e = ((Element) n);
			System.out.print("<" + e.getTagName() + ">");
			NodeList fils = n.getChildNodes();
			for (int i = 0; (i < fils.getLength()); i++) {
				afficher(fils.item(i));
			}
			System.out.println("</" + e.getTagName() + ">");
		} else if (n instanceof Document) {
			NodeList fils = n.getChildNodes();
			for (int i = 0; (i < fils.getLength()); i++) {
				afficher(fils.item(i));
			}
		}
	}

	public void startGame(String string) {

		for (Document document : listDocument) {
			Element racine = document.getDocumentElement();
			if (racine.getAttribute("name").equals(string)) {
				game = document;
				break;
			}
		}
	}
	
	public String[] getCodes(){
		
		String nodeid = "";
		int j = 0;
		NodeList situationlist = game.getDocumentElement().getChildNodes();
		String codess = "";
		for (int i = 0; i < situationlist.getLength(); i++) {
			if (situationlist.item(i) instanceof Element) {
				nodeid=(situationlist.item(i).getFirstChild()
						.getNextSibling().getFirstChild().getNodeValue());
				System.out.println("n:"+nodeid+";");
				if(nodeid!=""&&!nodeid.isEmpty()&&nodeid!=null){
					//codes[j] = nodeid;
					codess = codess==""?nodeid:codess+","+nodeid;
				}
			}
		}
		String[] codes = codess.split(","); // the hack pour String→String[]     \o/
		/* debug
		System.out.println("codess : "+codess);
		
		for (String string : codes) {
			System.out.println("have: "+string);
		}
		System.out.println("lengh:"+codes.length);
		//*/
		return codes;
	}
	
	

	public Node stepToNode(Step s) throws ParserConfigurationException {
		// TODO Auto-generated method stub
		DocumentBuilderFactory myfabrique;
		myfabrique = DocumentBuilderFactory.newInstance();
		DocumentBuilder myconstructeur = myfabrique.newDocumentBuilder();
		
		Document doc = myconstructeur.newDocument();
		doc.createElement("situation");
		Element situation = doc.createElement("situation");
	    //code
		Element code = doc.createElement("code");
	    code.appendChild(doc.createTextNode(Integer.toString(s.getCode())));
	    situation.appendChild(code);
	    // exposition
	    Element exposition = doc.createElement("exposition");
	    exposition.appendChild(doc.createTextNode(s.getExposition()));
	    situation.appendChild(exposition);
	    //question
	    Element question = doc.createElement("question");
	    question.appendChild(doc.createTextNode(s.getExposition()));
	    	//label
	    Element label = doc.createElement("label");
		label.appendChild(doc.createTextNode(s.getQuestion().getLabel()));
		question.appendChild(label);
			//choice
		Element choice = doc.createElement("choice");
			//awser
		Element anwser = doc.createElement("anwser");
		anwser.appendChild(doc.createAttribute("num"));
		for (int i : s.getQuestion().getNum()) {
			anwser.setAttribute("num", Integer.toString(i));
			anwser.appendChild(doc.createTextNode(s.getQuestion().getChoice().indexOf(i)+""));
			choice.appendChild(anwser);
		}
		question.appendChild(choice);
		situation.appendChild(question);
		//next
		Element next = doc.createElement("next");
		Element test = doc.createElement("test");
		Element codereponse = doc.createElement("codereponse");
		
		test.appendChild(doc.createAttribute("value"));
		
		for (int i : s.getNext().getValue()) {
			test.setAttribute("value", Integer.toString(i));
			codereponse.appendChild(doc.createTextNode(s.getNext().getCode().indexOf(i)+""));
			test.appendChild(codereponse);
			next.appendChild(test);
			test.removeChild(codereponse);
		}
		
		situation.appendChild(next);
		doc.appendChild(situation);
		System.out.println(doc.toString());
		
		return (Node) doc;
	}

	
	/*public Node stepToNode(Step s) {

		 return Node n;
	}*/

}
